package com.cargohu.aishouyu.operation.service.impl;

import com.cargohu.aishouyu.framework.exception.BusinessException;
import com.cargohu.aishouyu.framework.page.OrderByItem;
import com.cargohu.aishouyu.framework.page.Paging;
import com.cargohu.aishouyu.framework.service.impl.BaseServiceImpl;
import com.cargohu.aishouyu.operation.dto.AppVersionAddDTO;
import com.cargohu.aishouyu.operation.dto.AppVersionUpdateDTO;
import com.cargohu.aishouyu.operation.entity.AppVersion;
import com.cargohu.aishouyu.operation.mapper.AppVersionMapper;
import com.cargohu.aishouyu.operation.req.AppVersionRequest;
import com.cargohu.aishouyu.operation.resp.AppVersionDetailVo;
import com.cargohu.aishouyu.operation.resp.AppVersionResponse;
import com.cargohu.aishouyu.operation.service.AppVersionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * APP版本信息 服务实现类
 *
 * @author yww
 * @since 2023-11-29
 */
@Slf4j
@Service
public class AppVersionServiceImpl extends BaseServiceImpl<AppVersionMapper, AppVersion> implements AppVersionService {

    @Autowired
    private AppVersionMapper appVersionMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addAppVersion(AppVersionAddDTO appVersionAddDTO) throws Exception {
        AppVersion appVersion = new AppVersion();
        BeanUtils.copyProperties(appVersionAddDTO, appVersion);
        return save(appVersion);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateAppVersion(AppVersionUpdateDTO appVersionUpdateDTO) throws Exception {
        Long id = appVersionUpdateDTO.getId();
        AppVersion appVersion = getById(id);
        if (appVersion == null) {
            throw new BusinessException("APP版本信息不存在");
        }
        BeanUtils.copyProperties(appVersionUpdateDTO, appVersion);
        return updateById(appVersion);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteAppVersion(Long id) throws Exception {
        return removeById(id);
    }

    @Override
    public AppVersionDetailVo getAppVersionById(Long id) throws Exception {
        return appVersionMapper.getAppVersionById(id);
    }

    @Override
    public AppVersionDetailVo getLatestAppVersion(String platform) throws Exception {
        return appVersionMapper.getLatestAppVersion(platform);
    }

    @Override
    public Paging<AppVersionResponse> getAppVersionList(AppVersionRequest appVersionRequest) throws Exception {
        handlePage(appVersionRequest, OrderByItem.desc("id"));
        List<AppVersionResponse> list = appVersionMapper.getAppVersionList(appVersionRequest);
        Paging<AppVersionResponse> paging = new Paging<>(list);
        return paging;
    }

}
